package com.sky.handler;

import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 兜底业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public Result exceptionHandler(Throwable ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error("网络异常,请稍后重试");
    }
    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

//    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
//    public Result sqlIntegrityException(SQLIntegrityConstraintViolationException ex){
//        log.error("服务端异常", ex);
//        return Result.error("用户名不能重复");
//    }

    ////        String msg = allErrors.stream()
    ////                .map(ObjectError::getDefaultMessage)
    ////                .collect(Collectors.joining(";"));

    /**
     * 参数校验异常的处理器
     * */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodNotValid(MethodArgumentNotValidException ex){
        BindingResult bindingResult = ex.getBindingResult();
        // 拿到所有的错误信息
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        // 拼接所有的错误信息
        StringBuilder sb = new StringBuilder();
        for (ObjectError allError : allErrors) {
            String defaultMessage = allError.getDefaultMessage();
            sb.append(defaultMessage).append(";");
        }
        // 输出给客户端
        return Result.error(sb.toString());
    }
}
